import json
import requests
from langchain.tools import BaseTool
from pydantic import BaseModel, Field
from typing import Optional, Type


def get_wanianli_class(year: int, month: int, day: int) -> dict:
    """获取阴历日期信息"""
    url = (
        f"http://101.35.2.25/api/time/getzdday.php"
        f"?id=10007754&key=03105261003c7524ccf8607ad5425225"
        f"&nian={year}&yue={month}&ri={day}"
    )

    try:
        response = requests.get(
            url,
            headers={
                'User-Agent': 'Mozilla/5.0',
                'Accept': 'application/json'
            },
            timeout=10
        )
        response.raise_for_status()
        resp = response.json()
        print("get_wanianli_class ==> ", resp)
        return {
            "阴历年": resp.get("YIYEAR"),
            "阴历年中文": resp.get("nnian"),
            "阴历月": resp.get("YIMONTH"),
            "阴历月中文": resp.get("nyue"),
            "阴历日": resp.get("YIDAY"),
            "阴历日中文": resp.get("nri")
        }
    except requests.exceptions.RequestException as e:
        return {"error": f"请求失败: {str(e)}"}
    except json.JSONDecodeError:
        return {"error": "JSON解析失败"}
    except Exception as e:
        return {"error": f"未知错误: {str(e)}"}


class WanNianLiInput(BaseModel):
    """万年历工具的输入参数模型"""
    year: int = Field(..., description="年份，例如：2023")
    month: int = Field(..., description="月份，例如：9")
    day: int = Field(..., description="日期，例如：1")


class waNianLi(BaseTool):
    name: str = "wan_nian_li"
    description: str = "查询日期的阴历日期，输入格式：年、月、日（整数）"
    args_schema: Type[BaseModel] = WanNianLiInput

    def _run(self, year: int, month: int, day: int) -> dict:
        """执行工具主逻辑"""
        return get_wanianli_class(year, month, day)


if __name__ == '__main__':
    # 正确调用方式1：直接传递参数
    tool = waNianLi()

    result2 = tool.run({
        "year": "2025",
        "month": "9",
        "day": "1"
    })
    print(result2)
